
<script setup>
import {ref, reactive, defineProps} from 'vue';
import { ElMessage } from 'element-plus';
import {AddApp} from "@/api/app.js";
import {AppType} from "@/Constant/App/appType.js";
import {AppScoringStrategy} from "@/Constant/App/appScoringStrategy.js";
import {useRouter} from "vue-router";
import avatar from "@/assets/cover.jpg";
import {Plus} from "@element-plus/icons-vue";
import {userInfoStore} from "@/store/userInfoStore.js";
import {userTokenStore} from "@/store/userTokenStore.js";

const dialogVisible = ref(false);
const AppFormRef = ref(null);
const emit = defineEmits(['call-parent']); // 声明子组件可以触发的事件
const router = useRouter()
const props = defineProps({
  id: {
    type: String,
    default: "",
  },
});

const notifyParent = () => {
  emit('call-parent'); // 触发名为 'call-parent' 的自定义事件
};
const AppForm = reactive({
  appName: '',
  appDesc: '',
  appType: '',
  appIcon: '',
  scoringStrategy: '',
});

const rules = {
  appName: [
    { required: true, message: '请输入App名称', trigger: 'blur',},
    {
      min: 2,
      max: 20,
      message: '长度在 2 到 20 个字符',
      trigger: 'blur'
    }
  ],
  appDesc: [
    { required: true, message: '请输入app的描述', trigger: 'change' }
  ],
  appType: [
    { required: true, message: '请选择app的类型', trigger: 'change' }
  ],
  scoringStrategy:[
    {required: true, message: '请选择评分策略', trigger: 'change'}
  ]
};

const handleAvatarChange = (file) => {
  AppForm.appIcon = file.raw;
};

const AddrequestParam = ()=>{
  let param = {
    appName: AppForm.appName,
    appDesc: AppForm.appDesc,
    appType: AppForm.appType,
    appIcon: imgUrl.value,
    scoringStrategy: AppForm.scoringStrategy,
  }
  return param;
}

const submitForm = async () => {
  if (!AppFormRef.value) return;
  await AppFormRef.value.validate(async (valid) => {
    if (valid) {
      // 这里可以添加提交表单的逻辑
      console.log('提交的表单数据:', AppForm);
      const data = await AddApp(AddrequestParam(AppForm))
          .then((result) => {
            // 提交成功后的逻辑
            ElMessage.success('提交成功');
            notifyParent();
            // 重置表单
            AppFormRef.value.resetFields();
            dialogVisible.value = false;

            // 返回结果，以便在外部使用
            return result;
          })
          .catch((error) => {
            console.error('提交失败:', error);
            ElMessage.error('提交失败，请重试。');
            dialogVisible.value = false;
            // 抛出错误，以便在外部捕获
            throw error;
          });

      ElMessage.success('2秒后即将跳转到app详情界面');
      console.log("data: ", data);
      setTimeout(() => {
        router.push(`/mainPage/app/detail/${data.data}`); // 确保 data.data 是正确的路径
      }, 2000);
    } else {
      ElMessage.error('表单验证失败，请检查必填项。');
    }
  });
};

// 暴露一个方法用于显示对话框
const showAddAppDialog = () => {
  dialogVisible.value = true;
};

defineExpose({
  showAddAppDialog
});

const uploadRef = ref()
const InfoStore = userInfoStore();
const TokenStore = userTokenStore();
const imgUrl= ref(InfoStore.info.user_pic);
//笔记上传成功与否
const FileUpload = (result) => {
  imgUrl.value = result.data;
  print(imgUrl.value)
  console.log(result.data);
  console.log("上传成功");
  ElMessage.success("上传成功！");
};
const handleUploadError = (error) => {
  console.log(error);
  console.log("上传失败");
  ElMessage.error("上传失败");
};
</script>

<template>
  <el-dialog v-model="dialogVisible" title="添加应用" id="add-app-dialog">
    <el-form :model="AppForm" :rules="rules" ref="AppFormRef" label-width="120px">
      <el-form-item label="名称" prop="appName">
        <el-input v-model="AppForm.appName" placeholder="请输入app的名称"/>
          </el-form-item>
      <el-form-item label="描述" prop="appDesc">
        <el-input v-model="AppForm.appDesc" placeholder="请输入app的描述"/>
      </el-form-item>
      <el-form-item label="图片">
        <el-col :span="12" style="display: flex; flex-direction: column; align-items: center; gap: 12px;">
          <el-upload
              ref="uploadRef"
              class="avatar-uploader"
              :show-file-list="false"
              :headers = "{'Authorization':TokenStore.token}"
              action="/api/file/upload"
              name="file"
              :on-success="FileUpload"
              :on-error="handleUploadError"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" style="width: 200px; height: 200px; object-fit: cover;"  />
            <img v-else :src="avatar" width="278" />
          </el-upload>
          <br />
          <el-button type="primary" :icon="Plus" size="large"  @click="uploadRef.$el.querySelector('input').click()">
            选择图片
          </el-button>
        </el-col>
      </el-form-item>
      <el-form-item label="应用种类" prop="appType">
        <el-select v-model="AppForm.appType" placeholder="请选择app种类">
          <el-option v-for="(value,label) in AppType" :key="value" :label="label" :value="value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="评分标准" prop="scoringStrategy">
        <el-select v-model="AppForm.scoringStrategy" placeholder="请选择app评分标准">
          <el-option v-for="(value,label) in AppScoringStrategy" :key="value" :label="label" :value=value />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>


<style scoped>
/* 可以添加自定义样式 */
#add-app-dialog {
  z-index: 9999 !important;
}
</style>